<!DOCTYPE html>
<html class="x-admin-sm">

<head>
  <meta charset="UTF-8">
  <title>导表对比销库</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <link rel="stylesheet" href="../../css/font.css">
  <link rel="stylesheet" href="../../css/xadmin.css">
  <link rel="stylesheet" href="../../lib/layui/css/layui.css">
  <script type="text/javascript" src="../../lib/layui/layui.js" charset="utf-8"></script>
  <script type="text/javascript" src="../../js/xadmin.js"></script>
  <script src="../../js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="../../js/app.js" type="text/javascript" charset="utf-8"></script>
  <style type="text/css">
    .form-position {
      margin: 0.85rem;
      padding-top: 8px;
      background-color: white;

    }
  </style>
</head>

<body>
  <div class="x-nav">
    <span class="layui-breadcrumb">
      <a href="">首页</a>
      <a href="">演示</a>
      <a>
        <cite>导航元素</cite></a>
    </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
      onclick="location.reload()" title="刷新">
      <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
  </div>
  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-body ">
            <blockquote class="layui-elem-quote" style="margin-top: 10px; width: 97%;">
              <a href="http://47.94.20.119:8080/inventory_development/static/终端设备对比销库样表.xlsx">下载样表</a>
            </blockquote>
            <div class="layui-collapse" lay-filter="test">
              <div class="layui-colla-item">
                <h2 class="layui-colla-title">选择Excel表格入库<i class="layui-icon layui-colla-icon"></i></h2>
                <div class="layui-colla-content" style="display:flex;">

                  <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 4px;">
                    <input type="file" id='inputfilename'>
                  </div>
                  <div class="layui-inline layui-show-xs-block" style="margin-top: 7.2px;margin-left: 4px;">
                    <button class="layui-btn layui-btn-normal" onclick="readWorkbookFromLocalFile()">读取Excel表格</button>
                  </div>
                  <div class="layui-inline layui-show-xs-block layui-hide" id="compareWithEquipment"
                    style="margin-top: 7.2px;margin-left: 10px;">
                    <button class="layui-btn" onclick="compareWithEquipment_Ajax('2')">对比设备库</button>
                  </div>
                  <div class="layui-inline layui-show-xs-block layui-hide" id="compareWithTerminal"
                    style="margin-top: 7.2px;margin-left: 10px;">
                    <button class="layui-btn" onclick="compareWithTerminal_Ajax('1')">对比终端库</button>
                  </div>

                </div>
                <div id="result"></div>
              </div>
            </div>

            <table class="layui-hide" id="comparisonResults" lay-filter="comparisonResults"></table>
            <div style="display: none;" id="comparisonResultsToolBar">
              <div class="layui-btn-container">
                <button type="button" class="layui-btn layui-btn-sm" lay-event="reloadTable">刷新表格</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <script src="Select.js" type="text/javascript" charset="utf-8"></script> -->
    <!-- 导表入库 -->
    <script src="../../js/xlsx.core.min.js"></script>
    <script>
      // 创造workbook对象
      var newJsonData = null;

      function readWorkbookFromLocalFile() {
        var file = document.getElementById('inputfilename').files[0];
        if (file) {
          var reader = new FileReader();

          reader.onload = function (e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {
              type: 'binary'
            });
            readWorkbook(workbook);
          };
          reader.readAsBinaryString(file);

          $('#compareWithEquipment').removeClass('layui-hide');
          $('#compareWithTerminal').removeClass('layui-hide');
        } else {
          layer.msg('请先选择表格')
        }


      }

      // 将excel内容转换为csv和json
      var csv = '';
      var imeis = []; //存入串号在对比的时候实用

      function readWorkbook(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet的内容

        csv = XLSX.utils.sheet_to_csv(worksheet);
        document.getElementById('result').innerHTML = csv2table(csv);

        var json = XLSX.utils.sheet_to_json(worksheet);
        for (var i in json) {
          for (var key in json[i]) {
            if (key == '串号') {
              imeis.push(json[i][key]);
            }
          }
        }
      }

      // console.log(imeis);

      // 将csv转换成简单的表格，会忽略单元格合并，在第一行和第一列追加类似excel的索引
      function csv2table(csv) {
        var html = '<table class="layui-table layui-form">';
        var rows = csv.split('\n');
        rows.pop(); // 最后一行没用的
        rows.forEach(function (row, idx) {
          var columns = row.split(',');
          columns.unshift(idx + 1); // 添加行索引
          if (idx == 0) { // 添加列索引
            html += '<tr>';
            for (var i = 0; i < columns.length; i++) {
              html += '<th>' + (i == 0 ? '' : String.fromCharCode(65 + i - 1)) + '</th>';
            }
            html += '</tr>';
          }
          html += '<tr>';
          columns.forEach(function (column) {
            html += '<td>' + column + '</td>';
          });
          html += '</tr>';
        });
        html += '</table>';
        return html;
      }

      var Info = app.getUserGlobalInfo();
      console.log(Info);
      
      function compareWithTerminal_Ajax(categoryId) {
        if (imeis.length == 0) {
          layer.msg('请先选择表格！')
        } else {
          renderResults(categoryId, 'v1/repository/contrastEliminateInventoryTerminalByExcel/'+Info.userId);
        }
      }

      function compareWithEquipment_Ajax(categoryId) {
        if (imeis.length == 0) {
          layer.msg('请先选择表格！')
        } else {
          renderResults(categoryId, 'v1/repository/contrastEliminateInventoryEquipmentByExcel/'+Info.userId);
        }
      }

      function renderResults(categoryId, url) {

        layui.use(['jquery', 'layer', 'table', 'form'], function () {

          var operator = app.getUserGlobalInfo();
          var roleId = operator.roleId;
          var sessionId = (JSON.parse(localStorage.getItem("userInfo"))).sessionId;
          console.log(categoryId, url, imeis, roleId);

          var $ = layui.jquery;
          var layer = layui.layer;
          var table = layui.table;
          var form = layui.form;
          var msg = '';
          if (categoryId == '1') {
            msg = "确认要对比终端，实行销库操作吗？"
          } else {
            msg = "确认要对比设备，实行销库操作吗？"
          }

          layer.confirm( msg, {
            title: '提示信息',
            icon: 3,
            btn: ['确定', '取消'],
            yes: function (index) {
              var tableIns = table.render({
                elem: '#comparisonResults',
                url: app.ServerUrl + url,
                where: {
                  categoryId: categoryId,
                  imeis: imeis,
                  roleId: roleId
                },
                contentType: 'application/json;charset=UTF-8',
                headers: {
                  "Authorization": sessionId
                },
                method: 'post',
                title: 'comparisonResults',
                toolbar: '#comparisonResultsToolBar',
                defaultToolbar: ['filter', 'print', 'exports'],
                cellMinWidth: 200,
                done: (res, curr, count) => {
                  console.log(res, curr, count)
                  // imeis.length = 0; //清空串号数组
                  document.getElementById('result').innerHTML = "";
                },
                totalRow: true,
                page: true,
                limit: 10,
                limits: [5, 10, 20],
                text: {
                  none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
                },
                parseData: function (res) {
                  // console.log(res);
                  var result;
                  if (this.page.curr) {
                    result = res.objs[0].slice(this.limit * (this.page.curr - 1), this.limit * this.page
                      .curr);
                  } else {
                    result = res.objs[0].slice(0, this.limit);
                  }
                  // console.log(result);

                  var newResult = result.map(({
                    imei,
                    eliminateStatus
                  }) => {
                    return ({
                      imei,
                      eliminateStatus
                    })
                  })
                  console.log(newResult);
                  for (var i = 0; i < newResult.length; i++) {
                    var item = newResult[i];
                    if (item.eliminateStatus == 0) {
                      item.eliminateStatus = '未使用'
                    } else if (item.eliminateStatus == 1) {
                      item.eliminateStatus = '已使用（销库成功）'
                    } else if (item.eliminateStatus == 2) {
                      item.eliminateStatus = '二次销库'
                    }
                  }

                  return {
                    "resultStatus": res.resultStatus, //解析状态码
                    "resultIns": res.resultIns, //解析数据状态信息
                    "count": res.objs[0].length, //解析数据长度
                    "data": newResult //解析数据列表
                  };
                },
                response: {
                  statusName: 'resultStatus',
                  statusCode: 1,
                  msgName: 'resultIns'
                },
                cols: [
                  [{
                      field: 'imei',
                      title: '串号',
                      width: 400,
                      align: 'center'
                    },
                    {
                      field: 'eliminateStatus',
                      title: '状态',
                      width: 400,
                      align: 'center'
                    }
                  ]
                ]
              })
              layer.close(index);
            },
            cancel: function (index) {
              layer.close(index);
            }
          })

        })
      }
    </script>

    <script>
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?b393d153aeb26b46e9431fabaf0f6190";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
</body>

</html>